//获取app对象
const app = getApp()
//引入api接口
const { register } = require('../../utils/api')
const { returnBack } = require('../../utils/util')
//头像地址
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
	data: {
		//作为陪诊员登录
		navigatorProps: {
			url: '/pages/registerByWorker/registerByWorker',
			openType: 'navigate'
		},
		//用户信息
		userInfo: {
			avatarUrl: defaultAvatarUrl,
			nickname: '',
			tel: '',
			password: ''
		},
		hasUserInfo: false,
		canIUseGetUserProfile: wx.canIUse('getUserProfile'),
		canIUseNicknameComp: wx.canIUse('input.type.nickname'),
	},
	//注册
	userRegister() {
		let {avatarUrl} = this.data.userInfo
		const {nickname} = this.data.userInfo
		const {tel} = this.data.userInfo
		const {password} = this.data.userInfo
		const type = '1'
		if (tel == '') {
			wx.showToast({
				title: '请输入手机号',
				icon: 'error'
			})
		} else if (password == '') {
			wx.showToast({
				title: '请输入密码',
				icon: 'error'
			})
		} else {
			//如果头像是默认的，就置空
			if(avatarUrl == defaultAvatarUrl) {
				avatarUrl = ''
			}
			//发请求去后端查用户
			register(avatarUrl, nickname, tel, password, type, '').then((res) => {
				//如果请求成功，把返回的用户放到app里的currentUser中，重定向到主页
				if (res.code == 200) {
					app.globalData.currentUser = res.data
					console.log("当前登录用户为", app.globalData.currentUser);
					returnBack('/pages/hospital/users', '注册成功')
				}
			})
		}

	},
	//跳转登陆页面
	toLogin () {
		wx.redirectTo({
		  url: '/pages/login/login',
		})
	},
	//选择头像
	onChooseAvatar(e) {
		const avatarUrl = e.detail.avatarUrl
		this.setData({
			"userInfo.avatarUrl": avatarUrl
		})
	},
	//填写昵称
	changeNickname(e) {
		const nickname = e.detail.value
		this.setData({
			"userInfo.nickname": nickname
		})
	},
	//填写手机号
	changeTel(e) {
		const tel = e.detail.value
		this.setData({
			"userInfo.tel": tel
		})
	},
	//填写密码
	changePassword(e) {
		const password = e.detail.value
		this.setData({
			"userInfo.password": password
		})
	},
	//获取用户信息
	getUserProfile(e) {
		// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
		wx.getUserProfile({
			desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				console.log(res)
				this.setData({
					userInfo: res.userInfo,
					hasUserInfo: true
				})
			}
		})
	},
})